import Vue from 'vue'
import Vuex from 'vuex'
import { setCookie, getCookie } from '@/cookie'
import { setToken, getUserInfo } from '@/api/index'
import { asyncRoutes } from '@/router'
import { login } from '@/api/index'

Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        token: '',
        roles: [],
        routerKey: '',
        userInfo: {}
    },
    mutations: {
        setRouterKey(state, routerKey) {
            state.routerKey = routerKey
        },
        getRouterKey(state) {
            return state.routerKey
        },
        setToken(state, token) {
            state.token = token
            setToken(token)
        },
        setRoles(state, roles) {
            state.roles = roles
        },
        getRoles(state) {
            return state.roles
        }
    },
    actions: {
        login({ commit }, userInfo) {
            return new Promise((resolve, reject) => {
                login(userInfo).then(response => {
                    commit('setToken', response.data)
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },
        getUserInfo({ commit, state }) {
            return new Promise((resolve, reject) => {
                getUserInfo(state.token).then(response => {
                    console.log("setroles:" + response.roles);
                    commit('setRoles', response.roles)
                    resolve(response)
                }).catch(error => {
                    reject(error)
                })
            })
        },
        //动态生成路由
        generateRoutes(state, routes) {
            return asyncRoutes
        },
        //设置用户信息
        resetToken(state) {
            state.userInfo = {}
        }
    }
})

export default store